package Tree;

public class _297_SerializeandDeserializeBinaryTree {
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root==null) return "#@";
        String res = root.val + "@" + serialize(root.left) + serialize(root.right);
        return res;
    }

    int pos = 0;
    String[] vals;
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data.equals("#")) return null;
        this.vals = data.split("@");
        return deserializeHelper();
    }

    public TreeNode deserializeHelper() {
        if (vals[pos].equals("#")){
            pos++;
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(vals[pos++]));
        root.left = deserializeHelper();
        root.right = deserializeHelper();
        return root;
    }
}
